package edu.tgc.service.hrm;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.abyss.common.service.CommonCrudService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import edu.tgc.entity.hrm.IdCade;
import edu.tgc.repository.hrm.IdCadeRepository;
import edu.tgc.web.form.hrm.IdCadeForm;
@Service
public class IdCadeService extends CommonCrudService<IdCade, UUID> {
	
	@Autowired
	private IdCadeRepository idCadeDAO;

	public Page<IdCade> noUserPage(Pageable pageable) {
		Page<IdCade> page=idCadeDAO.findByIsUsed(false,pageable);
		return page;
	}

	@Transactional
	public void save(MultipartFile file, IdCadeForm form) throws IllegalStateException, IOException {
		IdCade idCade=idCadeDAO.findByIdNo(form.getIdNo());
		if(idCade==null){
			idCade=new IdCade(UUID.randomUUID());
		}
		BeanUtils.copyProperties(form, idCade,"id","photo","isUsed");
		File path=new File(IdCade.getPath());
		if(!path.exists()){
			path.mkdirs();
		}
		File saveFile=new File(path, idCade.getIdNo());
		if(file!=null){
			String originalFilename = file.getOriginalFilename();
			String filename = new File(originalFilename).getName();
			idCade.setPhoto(filename);
			file.transferTo(saveFile);
		}/*else{
			if(saveFile.exists()){
				saveFile.delete();
			}
			idCade.setPhoto(null);
		}*/
		idCadeDAO.save(idCade);
	}

    /****
     * 获取下载中文文件名的网络字符串
     * 
     * @param request
     *            请求对象
     * @param fileName
     *            文件名
     * @return
     */
    public String getStr(HttpServletRequest request, String fileName) {
        String downloadFileName = null;
        String agent = request.getHeader("USER-AGENT");
        try {
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            } else {
                downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }

	public void imageStream(String idNo, HttpServletRequest request, HttpServletResponse response) throws IOException {
		IdCade idCade=idCadeDAO.findByIdNo(idNo);
		//String filename=idCade.getPhoto();
		//filename=getStr(request, filename);
		response.reset();
		response.setHeader("Pragma", "No-cache");  
		response.setHeader("Cache-Control", "no-cache");  
		response.setDateHeader("Expires", 0L);  
		ServletOutputStream out = response.getOutputStream();
		if(idCade!=null){
			File file=new File(IdCade.getPath(), idCade.getIdNo());
			if(file.exists()){
				response.setHeader("Content-Length", file.length() + "");  
				byte[] buf = new byte[4096];
				InputStream in = new FileInputStream(file);
				int size;
				while ((size = in.read(buf)) != -1) {
					out.write(buf, 0, size);
				}
				in.close();
				out.flush();
				out.close();
			}else{
				//String path=request.getServletContext().getRealPath("/")+"/upload";
				//String path=request1.getServletPath()+"/upload";
				String path=System.getProperty("evan.webapp")+"\\statics\\images";
				file=new File(path,"nophoto.jpg");
				response.setHeader("Content-Length", file.length() + "");  
				byte[] buf = new byte[4096];
				InputStream in = new FileInputStream(file);
				int size;
				while ((size = in.read(buf)) != -1) {
					out.write(buf, 0, size);
				}
				in.close();
				out.flush();
				out.close();
			}
		}else{
			String path=System.getProperty("evan.webapp")+"\\statics\\images";
			File file=new File(path,"nophoto.jpg");
			response.setHeader("Content-Length", file.length() + "");  
			byte[] buf = new byte[4096];
			InputStream in = new FileInputStream(file);
			int size;
			while ((size = in.read(buf)) != -1) {
				out.write(buf, 0, size);
			}
			in.close();
			out.flush();
			out.close();
		}
		
	}
	
	public IdCade findById(UUID id){
		return idCadeDAO.findOne(id);
	}
	
	

}
